package com.dh.blog.utils;

import java.text.SimpleDateFormat;
import java.util.Date;

public class TokenUtils {
	private static final String appId = "davidhua19965201314";
	/**
	 * 以应用id，用户身份信息和时间戳生成令牌信息
	 * @param identify
	 * @return
	 */
	public static String generateToken(String identify,Date date) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		String timeStamp = formatter.format(date);
		try{
			return Encrypter.md5Digest(appId + identify + timeStamp); 
		}catch (Exception e){
			e.printStackTrace();
			return null;
		}
	}
	/**
	 * 将用户身份信息和时间戳用BASE64加密
	 * @param identify
	 * @return
	 */
	public static String generateAuth(String identify,Date date) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		String timeStamp = formatter.format(date);
		try{
			return Encrypter.base64Encoder(identify+timeStamp);
		}catch(Exception e){
			e.printStackTrace();
			return "";
		}
	}
	/**
	 * 验证身份令牌的有效性(重新加密再进行匹配)
	 * @param token
	 * @param auth
	 * @return
	 * @throws Exception
	 */
	public static boolean validate(String token, String auth) throws Exception {
		//解码从客户端过来的身份信息
		String authDecode = Encrypter.base64Decoder(auth);
		String identify = getUserFromAuth(authDecode);
		//yyyyMMddHHmmss
		String timeStamp = getTimeStampFromAuth(authDecode);
		String signString = Encrypter.md5Digest(appId + identify + timeStamp);
		if(token.equals(signString)){
			return true;
		}
		return false;
	}

	public static String getUserFromAuth(String authDecode) {
		String userName = authDecode.substring(0,authDecode.length() - 14);
		return userName;
	}

	public static String getTimeStampFromAuth(String authDecode) {
		String timeStamp = authDecode.substring(authDecode.length() - 14);
		return timeStamp;
	}
	
}
